<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <s8cript src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></s8cript>
  <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
    integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
    integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
    crossorigin="anonymous"></script>
</head>
<style>
  *{
    padding: 0;
    margin: 0;
  }
  .table {
    width: 1200px;
    margin: auto;
    margin-top: 10px;
  }

  th,
  td {
    text-align: center;
  }

  .box {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    top: 0;
    left: 0;
  }
  .span{
    font-size: 20px;
    position: absolute;
    top: 66px;
    left: 560px;
  }
  .jia{
    background-color: #ccc;
  }
</style>

<body>
  <!-- 添加商品表单 -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
          <h4 class="modal-title" id="myModalLabel">添加商品</h4>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="goodsName">商品名称</label>
            <input type="text" class="form-control" id="goodsName" placeholder="商品名称" />
          </div>

          <div class="form-group">
            <label for="goodsPrice">商品价格</label>
            <input type="number" class="form-control" id="goodsPrice" placeholder="商品价格" />
          </div>
          <div class="form-group">
            <label for="goodsStock">商品库存</label>
            <input type="text" class="form-control" id="goodsStock" placeholder="商品库存" />
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            取消添加
          </button>
          <button type="button" id="saveBtn" class="btn btn-primary">
            保存添加
          </button>
        </div>
      </div>
    </div>
  </div>
  <div class="box">
    <p>
    <span class="span">搜索:</span>  <input type="text" class="form-control"  placeholder="商品名称" id="keyword" style=" margin-top: 46px;" />
    </p>
    <p>
      <button class="btn btn-default" data-toggle="modal" data-target="#myModal"
        style="width: 100px; height: 50px; margin-left: 65%; margin-top: 56px">
        添加商品
      </button>
    </p>

  </div>

  <div id="goodsList">


    <table id="table" class="table table-bordered">
      <thead>
        <tr>
          <th>商品名称</th>
          <th>商品价格</th>
          <th>商品库存</th>
          <th>添加时间</th>
          <th>商品操作</th>
        </tr>
      </thead>
      <tbody id="tbody1"></tbody>
    </table>
  </div>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th><input type="checkbox" id="all" /></th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>商品数量</th>
      </tr>
    </thead>
    <tbody id="tbody2"></tbody>
  </table>

  <div style="width: 100%; text-align: center; font-size: 22px; margin-top: 20px">
    <p>总价：<span id="totalPrice">0</span>￥</p>
  </div>
</body>
<script>
  var goodsList = []
  var shopCarList = [],
    id
  //页面加载
  $(function () {
    $('#keyword').on('keyup', function () {
      keywordSubmit()
    })
    function keywordSubmit() {
      // console.log(keywordSubmit);
      const keyword = $.trim($("#keyword").val());
      console.log(keyword);
      $('#tbody1 tr').each(function () {
        const text = $(this).text();
        if (keyword) {
          if (new RegExp(keyword.toLowerCase()).test(text.toLowerCase())) {
            $(this).show();
          } else {
            $(this).hide();
          }
        } else {
          $(this).show();
        }
      });
    }

    //生成自增ID
    id = function () {
      var num = localStorage.getItem('gid')
        ? Number(localStorage.getItem('gid'))
        : 0
      num++
      localStorage.setItem('gid', num)
      return num
    }
    //显示商品列表
    showGoodsList()
    //显示购物车列表
    showShopCarList()
    countPrice()
    //全选
    $('#all').click(function () {
      $('#tbody2 input').prop('checked', $(this).prop('checked'))

      for (let i in shopCarList) {
        shopCarList[i].status = $(this).prop('checked')
      }
      saveData()
      countPrice()
    })
    $('#tbody2').on('change', function () {
      var index = $(event.target).attr('data-id')
      if ($(event.target).attr('type') == 'number') {
        var num = $(event.target).val()
        console.log(shopCarList[index].num, num)
        var n = shopCarList[index].num - Number(num)
        goodsList.findIndex(function (item) {
          if (item.id == shopCarList[index].id) {
            item.stock += n
          }
        })
        shopCarList[index].num = num
        localStorage.setItem('goodsList', JSON.stringify(goodsList))
        showGoodsList()
      } else {
        //复选改变时 要存一下当前状态
        shopCarList[index].status = $(event.target).prop('checked')
      }
      saveData()
      countPrice()
    })
    //点击添加商品
    $('#saveBtn').click(function () {
      var goodsName = $('#goodsName').val()
      var goodsPrice = $('#goodsPrice').val()
      var goodsStock = $('#goodsStock').val()
      if (goodsName == '' || goodsPrice == '' || goodsStock == '') {
        alert('请填写完整信息')
        return
      }
      var goods = {
        id: id(),
        name: goodsName,
        price: goodsPrice,
        stock: goodsStock,
        add_time: new Date().toLocaleString(),
      }
      goodsList.push(goods)
      localStorage.setItem('goodsList', JSON.stringify(goodsList))
      showGoodsList()
      $('#myModal').modal('hide')
    })

    $('#tbody1').dblclick(function () {
      if (event.target.tagName == 'TD') {
        var tdObj = $(event.target)
        var strHtml = $(
          "<input type='text' name=" +
          $(event.target).attr('data-key') +
          " class='form-control' onblur='saveEdit(this," +
          $(event.target).attr('data-index') +
          ")' value='" +
          tdObj.html() +
          "'/>"
        )
        tdObj.html(strHtml)
        strHtml.focus()
      }
    })
  })
  function saveEdit(obj, index) {
    var shopIndex = shopCarList.findIndex(function (item) {
      if (item.id == goodsList[index].id) {
        return true
      }
    })
    switch ($(obj).attr('name')) {
      case 'gname':
        goodsList[index].name = $(obj).val()
        shopCarList[shopIndex].name = $(obj).val()
        break
      case 'price':
        goodsList[index].price = $(obj).val()
        shopCarList[shopIndex].price = $(obj).val()
        break
      case 'stock':
        goodsList[index].stock = $(obj).val()
        shopCarList[shopIndex].stock = $(obj).val()
        break
    }
    saveData()
    localStorage.setItem('goodsList', JSON.stringify(goodsList))
    showGoodsList()
    showShopCarList()
    countPrice()
  }
  //显示商品列表
  function showGoodsList() {
    goodsList = localStorage.getItem('goodsList')
      ? JSON.parse(localStorage.getItem('goodsList'))
      : []
    var str = ''
    for (let i in goodsList) {
      str += `<tr>
                    <td data-index="${i}" data-key="gname">${goodsList[i].name}</td>
                    <td data-index="${i}" data-key="price">${goodsList[i].price}</td>
                    <td data-index="${i}" data-key="stock">${goodsList[i].stock}</td>
                    <td>${goodsList[i].add_time}</td>
                    <td>
                        <button class="btn jia" onclick="addShopCar(${i})" data-id="${goodsList[i].id}">加入购物车</button>
                        <button class="btn btn-default" onclick="del(${i})" data-id="${goodsList[i].id}">删除</button>
                    </td>
                 </tr>`
    }
    $('#tbody1').html(str)
  }

  //删除商品
  function del(index) {
    var x = shopCarList.findIndex(function (item, i) {
      if (item.id == goodsList[index].id) {
        return true
      }
    })
    shopCarList.splice(x, 1)
    goodsList.splice(index, 1)
    localStorage.setItem('goodsList', JSON.stringify(goodsList))
    showGoodsList()
    saveData()
    showShopCarList()
    countPrice()
  }
  //添加到购物车
  function addShopCar(index) {
    var goods = goodsList[index]
    //减少库存
    if (goodsList[index].stock == 0) {
      alert('库存不足')
      return
    }
    goodsList[index].stock--
    localStorage.setItem('goodsList', JSON.stringify(goodsList))
    showGoodsList()
    //检查数组对象中是否存在
    var isHas = shopCarList.every(function (item) {
      if (item.id == goods.id) {
        return false
      }
      return true
    })
    if (isHas) {
      shopCarList.push({
        id: goods.id,
        name: goods.name,
        price: goods.price,
        num: 1,
      })
    } else {
      shopCarList[index].num++
    }
    saveData()
    showShopCarList()
    countPrice()
  }
  //统计价格
  function countPrice() {
    var total = 0
    $('#tbody2 input:checkbox').each(function (index, item) {
      if ($(item).prop('checked')) {
        total += shopCarList[index].price * shopCarList[index].num
      }
    })
    $('#totalPrice').html(total)
  }
  //显示购物车列表
  function showShopCarList() {
    //获取本地存储数据
    shopCarList = localStorage.getItem('shopCarList')
      ? JSON.parse(localStorage.getItem('shopCarList'))
      : shopCarList
    var strHtml = ''
    for (let i in shopCarList) {
      var strBox = shopCarList[i].status ? `checked` : ``
      strHtml += `
                <tr>
                    <td>
                        <input type="checkbox" class="check" ${strBox} data-id="${i}" />
                    </td>
                    <td>${shopCarList[i].name}</td>
                    <td>${shopCarList[i].price}</td>
                    <td>
                        <input type="button" value="-" onclick="updateNumDown(${i},this)" class="btn btn-default reduce" />
                        <input type="number" data-id="${i}" min="0"  style="width:50px" value="${shopCarList[i].num}" class="num" />
                        <input type="button" value="+" onclick="updateNumUp(${i},this)" class="btn btn-default add" />
                    </td>
                </tr>
            `
    }
    $('#tbody2').html(strHtml)
  }
  //数量-- 或 ++
  function updateNumDown(index, obj) {
    for (let i in goodsList) {
      if (shopCarList[index].id == goodsList[i].id) {
        if (shopCarList[index].num == 0) {
          alert('不能再减少了')
          return
        }
        shopCarList[index].num--
        goodsList[i].stock++
        break
      }
    }
    localStorage.setItem('goodsList', JSON.stringify(goodsList))
    showGoodsList()
    $(obj).next().val(shopCarList[index].num)
    countPrice()
    saveData()
  }
  function updateNumUp(index, obj) {
    for (let i in goodsList) {
      if (shopCarList[index].id == goodsList[i].id) {
        if (goodsList[i].stock == 0) {
          alert('库存不足')
          return
        }
        shopCarList[index].num++
        goodsList[i].stock--
        break
      }
    }
    localStorage.setItem('goodsList', JSON.stringify(goodsList))
    showGoodsList()
    $(obj).prev().val(shopCarList[index].num)
    countPrice()
    saveData()
  }
  //存储本地数据
  function saveData() {
    localStorage.setItem('shopCarList', JSON.stringify(shopCarList))
  }
</script>

</html>